package com.spring.factory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author SpringWang
 * @date 2021/5/20
 */
public class BeansFactory {

    private static final Map<String, Object> map = new HashMap<>();

    static {
        InputStream inputStream = BeansFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            List<Element> beans = rootElement.selectNodes("//bean");
            for (Element bean : beans) {
                String id = bean.attributeValue("id");
                String aClass = bean.attributeValue("class");
                Class<?> clazz = Class.forName(aClass);
                Object o = clazz.getConstructor().newInstance();

                map.put(id, o);
            }

            List<Element> properties = rootElement.selectNodes("//property");
            for (Element property : properties) {
                String name = property.attributeValue("name");
                String ref = property.attributeValue("ref");

                Element parent = property.getParent();
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                Method[] methods = parentObject.getClass().getMethods();

                for (Method method : methods) {
                    if (method.getName().equalsIgnoreCase("set" + name)) {
                        method.invoke(parent, map.get(ref));
                    }
                }
                // 把处理之后的parentObject重新放到map
                map.put(parentId, parentObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
